from django.contrib import admin
from django.http import HttpResponseRedirect
from .models import *
from django.urls import path
from django.utils.html import format_html
from django import forms
import json
from django.utils.safestring import mark_safe

@admin.register(OllamaList)
class OllamaListAdmin(admin.ModelAdmin):
    # listdisplay设置要显示在列表中的字段（id字段是Django模型的默认主键）
    list_display = ['id', 'models_name', 'model_details',]
    # list_per_page设置每页显示多少条记录，默认是100条
    list_per_page = 100
    # ordering设置默认排序字段，负号表示降序排序
    ordering = ('-id',)
    # 筛选器
    # list_filter = ('car_model',)  # 过滤器
    search_fields = ('models_name',)  # 搜索字段
    exclude = ['model_details', ]
    readonly_fields = ['models_name','model_details_display']

    def model_details_display(self, obj):
        try:
            # 将 JSON 数据进行格式化
            formatted_json = json.dumps(obj.model_details, indent=4, ensure_ascii=False)
            # 使用 <pre> 标签来保留格式显示 JSON 数据
            return format_html('<pre>{}</pre>', formatted_json)
        except (TypeError, ValueError):
            return str(obj.model_details)

    model_details_display.short_description = '模型详情'

# Register your models here.
@admin.register(ChatAppKey)
class ChatAppKeyAdmin(admin.ModelAdmin):
    # 隐藏默认的新增按钮
    def has_add_permission(self, request):
        return False
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('create_app_key/', self.create_app_key, name='create_app_key'),
        ]
        return custom_urls + urls
    def create_app_key(self, request):
        current_user = request.user
        if current_user.is_authenticated:
            ChatAppKey.objects.create(create_user=current_user)
            self.message_user(request, "AppKey 已成功创建。")
        else:
            self.message_user(request, "请先登录。", level='ERROR')
        return HttpResponseRedirect("../")
    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}
        # 添加自定义按钮到上下文
        extra_context['custom_add_button'] = format_html(
            '<a href="{}" class="addlink">创建 AppKey</a>',
            request.path + 'create_app_key/'
        )
        return super().changelist_view(request, extra_context=extra_context)
    # listdisplay设置要显示在列表中的字段（id字段是Django模型的默认主键）
    list_display = ['id', 'create_user', 'app_key','select_model', 'created_at', 'last_used_at', 'token_get_num', 'api_get_num']
    # list_per_page设置每页显示多少条记录，默认是100条
    list_per_page = 100
    # ordering设置默认排序字段，负号表示降序排序
    ordering = ('-created_at',)
    # 筛选器
    # list_filter = ('car_model',)  # 过滤器
    search_fields = ('create_user',)  # 搜索字段

    def get_form(self, request, obj=None, **kwargs):
        class CustomChatAppKeyForm(forms.ModelForm):
            custom_select_model = forms.ChoiceField(choices=[])

            class Meta:
                model = ChatAppKey
                fields = '__all__'
                exclude = ['select_model']  # 排除原 select_model 字段

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                ollama_models = OllamaList.objects.values_list('models_name', 'models_name')
                self.fields['custom_select_model'].choices = ollama_models
                if obj and obj.select_model:
                    self.initial['custom_select_model'] = obj.select_model

            def save(self, commit=True):
                instance = super().save(commit=False)
                instance.select_model = self.cleaned_data['custom_select_model']
                if commit:
                    instance.save()
                return instance

        kwargs['form'] = CustomChatAppKeyForm
        return super().get_form(request, obj, **kwargs)

    def custom_select_model_display(self, obj):
        return obj.select_model


    readonly_fields = ['app_key','select_model','create_user','created_at','last_used_at','token_get_num','api_get_num']
    custom_select_model_display.short_description = '选择的模型'



@admin.register(ChatHistory)
class ChatHistoryAdmin(admin.ModelAdmin):
    # listdisplay设置要显示在列表中的字段（id字段是Django模型的默认主键）
    list_display = ['id', 'from_app_key', 'chat_title','created_at','last_used_at','chat_json']
    # list_per_page设置每页显示多少条记录，默认是100条
    list_per_page = 100
    # ordering设置默认排序字段，负号表示降序排序
    ordering = ('-last_used_at',)
    readonly_fields = ['from_app_key','from_user_id','from_app_id','select_model','system_model','chat_title','chat_json','created_at','last_used_at']
    # 筛选器
    list_filter = ('created_at',)  # 过滤器
    search_fields = ('from_user_id', 'from_app_id', 'chat_title')  # 搜索字段